use std::{collections::HashMap, fs::read_to_string};

struct Table {
    s2t: HashMap<String, String>,
    t2s: HashMap<String, String>,
}

impl Table {
    /// read data from a local file
    fn build() -> Self {
        let mut s2t = HashMap::new();
        let mut t2s = HashMap::new();
        for line in read_to_string("../../topic1/solutiont6/s2t")
            .unwrap()
            .lines()
        {
            if line.trim().is_empty() {
                continue;
            }
            let mut it = line.split("  ");
            let simp = it.next().unwrap();
            let trad = it.next().unwrap();
            s2t.insert(simp.to_owned(), trad.to_owned());
        }

        for line in read_to_string("../../topic1/solutiont6/t2s")
            .unwrap()
            .lines()
        {
            if line.trim().is_empty() {
                continue;
            }
            let mut it = line.split("  ");
            let trad = it.next().unwrap();
            let simp = it.next().unwrap();
            t2s.insert(trad.to_owned(), simp.to_owned());
        }
        Self { s2t, t2s }
    }
    fn s2t(&self, simp: &str) -> String {
        if let Some(trad) = self.s2t.get(simp) {
            trad.to_owned()
        } else {
            simp.chars().map(|c| self.s2t_c(c)).collect()
        }
    }
    fn t2s(&self, trad: &str) -> String {
        if let Some(simp) = self.t2s.get(trad) {
            simp.to_owned()
        } else {
            trad.chars().map(|c| self.t2s_c(c)).collect()
        }
    }
    fn s2t_c(&self, c: char) -> String {
        if let Some(t) = self.s2t.get(&c.to_string()) {
            t.to_owned()
        } else {
            c.to_string()
        }
    }
    fn t2s_c(&self, c: char) -> String {
        if let Some(s) = self.t2s.get(&c.to_string()) {
            s.to_owned()
        } else {
            c.to_string()
        }
    }
}

pub fn converter(input: &str, tp: &str) -> String {
    let table = Table::build();
    if tp == "s2t" {
        table.s2t(input)
    } else {
        table.t2s(input)
    }
}
